export const debounce = {
  mounted(el: Element, binding: any) {
    let timer: any = null
    el.addEventListener('click', () => {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout(() => {
        binding.value()
      }, 500)
    })
  }
}

// 可以指定触发事件类型和时间的写法
export const debounce2 = {
  mounted: function (el: any, { value: { fn, event = 'click', time = 300 } }: any) {
    //没绑定函数直接返回
    if (typeof fn !== 'function') return
    el.timer = null
    //监听点击事件，限定事件内如果再次点击则清空定时器并重新定时
    el.addEventListener(event, () => {
      if (el.timer) {
        clearTimeout(el.timer)
      }
      el.timer = setTimeout(() => {
        fn()
      }, time)
    })
  }
}

export default debounce
